package com.example.lianjuan.ui.custom;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.lianjuan.R;
import com.example.lianjuan.Utils.LogUtils;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TextFlowLayout extends ViewGroup {
    public static final float DEFAULT_SPACE = 10;
    private float mItemHorizontalSpace = DEFAULT_SPACE;
    private float mItemVerticalSpace = DEFAULT_SPACE;
    private List<String> mTextView = new ArrayList<>();
    private int selfWidth;
    private onItemFlowClickListener listener = null;

    public TextFlowLayout(Context context) {
        this(context, null);
    }

    public TextFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TextFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //自定义属性
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextFlowLayout);
        mItemHorizontalSpace = ta.getDimension(R.styleable.TextFlowLayout_horizontalSpace, DEFAULT_SPACE);
        mItemVerticalSpace = ta.getDimension(R.styleable.TextFlowLayout_verticalSpace, DEFAULT_SPACE);
        ta.recycle();
    }

    /**
     * 摆放布局
     *
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int topOffSet = 0;
        LogUtils.d(this, "lineList.size----->" + lineList.size());
        for (List<View> views : lineList) {
            int leftOffSet = 0;
            topOffSet += (int) mItemVerticalSpace;
            for (View view : views) {
                leftOffSet += (int) mItemHorizontalSpace;
                view.layout(leftOffSet, topOffSet, leftOffSet + view.getMeasuredWidth(), topOffSet + view.getMeasuredHeight());
                leftOffSet += view.getMeasuredWidth();
            }
            topOffSet += views.get(0).getMeasuredHeight();
        }
    }

    public void setTextList(List<String> textList) {
        //清空子视图
        removeAllViews();
        this.mTextView.clear();
        this.mTextView.addAll(textList);
        //集合翻转
        Collections.reverse(this.mTextView);
        //遍历数据，把数据和textView绑定
        for (String text : this.mTextView) {
            //添加子view
            TextView itme = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.text_flow_layout, this, false);
            itme.setText(text);
            itme.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (listener != null) {
                        listener.onItemFlowClick(text);
                    }
                }
            });
            addView(itme);
        }
    }

    private List<List<View>> lineList = new ArrayList<>();

    /**
     * 测量
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //标准方法：当控件为WRAP_CONTENT时，防止自定义控件WRAP_CONTENT失效，先对自己测量
//        // 获取宽-测量规则的模式和大小
//        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
//        //当控件为WRAP_CONTENT时，防止自定义控件WRAP_CONTENT失效，先对自己测量
//        if (getLayoutParams().height == ViewGroup.LayoutParams.WRAP_CONTENT) {
//            setMeasuredDimension(widthSize, 0);
//            if (getChildCount() == 0) {
//                return;
//            }
//        }
        //onMeasure多次绘制，先清空
        lineList.clear();
        List<View> line = null;
        selfWidth = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
        //当子view没有，直接测量自己
        if (getChildCount() == 0) {
            setMeasuredDimension(selfWidth, 0);
            return;
        }
        //测量孩子
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View itemView = getChildAt(i);
            if (itemView.getVisibility() != VISIBLE) {
                //不显示则不测量
                continue;
            }
            //测量前
            LogUtils.d(this, "itemView.getMeasuredWidth---->" + itemView.getMeasuredWidth() + "||||" + "itemView.getMeasuredHeight---->" + itemView.getMeasuredHeight());
            measureChild(itemView, widthMeasureSpec, heightMeasureSpec);
            //测量后
            LogUtils.d(this, "itemView.getMeasuredWidth---->" + itemView.getMeasuredWidth() + "||||" + "itemView.getMeasuredHeight---->" + itemView.getMeasuredHeight());
            //第一次直接创建，或者不能添加itemView
            if (line == null || !canBeAdd(itemView, line)) {
                line = createNewLine(itemView);
            } else {
                //能添加，直接添加
                line.add(itemView);
            }
        }
        //高度
        int selfHeight = (int) ((getChildAt(0).getMeasuredHeight() * lineList.size()) + (mItemVerticalSpace * (lineList.size() + 1)) + 0.5f);
        //根据实际情况，再次测量自己
        setMeasuredDimension(selfWidth, selfHeight);
    }

    /**
     * 把itemView添加到集合中
     *
     * @param itemView
     */
    private List<View> createNewLine(View itemView) {
        List<View> line = new ArrayList<>();
        line.add(itemView);
        lineList.add(line);
        return line;
    }

    /**
     * 判断是否能继续添加
     *
     * @param itemView
     * @param line
     * @return
     */
    private boolean canBeAdd(View itemView, List<View> line) {
        //所有已经添加的itemView宽度加上((line.size()+1)*mItemHorizontalSpace)+itemView.getMeasuredWidth())
        //条件：如果小于/等于当前控件的宽带,则添加,否则不能添加
        //需要添加控件的宽度
        int total = itemView.getMeasuredWidth();
        for (View view : line) {
            //叠加所有控件的宽度
            total += view.getMeasuredWidth();
        }
        //水平控件间距的宽度（float转int四舍五入）
        total += (int) ((line.size() + 1) * mItemHorizontalSpace + 0.5f);
        return total <= selfWidth;
    }

    public int getHistorySize() {
        return mTextView.size();
    }

    public void setItemFlowClickListener(onItemFlowClickListener listener) {
        this.listener = listener;
    }


    public interface onItemFlowClickListener {
        void onItemFlowClick(String text);
    }
}
